package cn.deschen.eshop.auth.hanlders;

import cn.deschen.eshop.common.api.CommonRes;
import cn.deschen.eshop.common.enums.GlobalEnum;
import cn.hutool.json.JSONUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author hanbin_chen
 * @Description 自定义返回结果：未登录或登录过期
 * @DateTime 2021/1/22 14:16
 * @Version V1.0.0
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(
                JSONUtil.parse(CommonRes.failure(GlobalEnum.UNAUTHORIZED, authException.getMessage())));
        response.getWriter().flush();
    }
}
